package com.cht.commonUtil.infra;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.cht.commonUtil.structure.S5;
import com.cht.commonUtil.webInit.SP;
import com.cht.commonUtil.widgets.Widgets;
import com.google.gson.Gson;

public class QueryFTPconnectionInfo extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding( SP.UIcodeSet );
		response.setContentType("application/json");
		response.setCharacterEncoding( SP.UIcodeSet );
		
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		
		String subsysId = request.getParameter("subsysId");
		
		List<S5> scis = new ArrayList<S5>();	//儲存此子系統下，連線資訊
		
		try {
			String sql = "SELECT t2.ftpLoginSN,t2.loginURL,t2.id,t2.pwd,t2.path FROM mpsubsys2ftp t1, ftplogin t2 WHERE t1.ftploginSN=t2.ftpLoginSN AND t1.subsysId=?";
			conn = Widgets.getConn();	
			ps = conn.prepareStatement(sql);
			ps.setString(1, subsysId);	
			rs = ps.executeQuery();
			while( rs.next() ) {
				S5 sci = new S5();
				sci.setS1( rs.getString("loginURL") );
				sci.setS2( rs.getString("id") );
				sci.setS3( rs.getString("pwd") );
				sci.setS4( rs.getString("path") );
				sci.setS5( String.valueOf( rs.getInt("ftpLoginSN") )  );
				scis.add(sci);
			}
		} catch ( Exception e) {
			Widgets.errLog(e);
		} finally {
			try {
				if ( rs != null ) { rs.close(); }
				if ( ps!= null ) { ps.close(); }
				if ( conn!= null ) { conn.close(); }
			} catch (SQLException e) {e.printStackTrace(); }
		}
		
		response.getWriter().write(new Gson().toJson(scis));
	}

}
